import { Tag } from 'antd';
import React from 'react';

// 格式化价格
export const formatPrice = (price: number | string): string => {
  const numPrice = typeof price === 'string' ? parseFloat(price) : price;
  return `¥${numPrice.toFixed(2)}`;
};

// 格式化日期
export const formatDate = (date: string | Date): string => {
  try {
    return date ? new Date(date).toLocaleDateString() : '-';
  } catch (error) {
    return '-';
  }
};

// 格式化日期时间
export const formatDateTime = (date: string | Date): string => {
  try {
    return date ? new Date(date).toLocaleString() : '-';
  } catch (error) {
    return '-';
  }
};

// 获取状态标签
export const getStatusTag = (status: string): React.ReactElement => {
  const statusConfig: Record<string, { color: string; text: string }> = {
    active: { color: 'green', text: '上架中' },
    inactive: { color: 'red', text: '已下架' },
    out_of_stock: { color: 'orange', text: '缺货' },
    pending: { color: 'blue', text: '待审核' },
    approved: { color: 'green', text: '已通过' },
    rejected: { color: 'red', text: '已拒绝' },
    suspended: { color: 'orange', text: '已暂停' },
    draft: { color: 'gray', text: '草稿' },
  };

  const config = statusConfig[status] || { color: 'default', text: status };
  return <Tag color={config.color}>{config.text}</Tag>;
};

// 获取库存状态
export const getStockStatus = (stock: number): React.ReactElement => {
  if (stock === 0) {
    return <Tag color="red">缺货</Tag>;
  } else if (stock < 10) {
    return <Tag color="orange">库存紧张({stock})</Tag>;
  } else {
    return <Tag color="green">库存充足({stock})</Tag>;
  }
};

// 获取用户角色标签
export const getRoleTag = (role: string): React.ReactElement => {
  const roleConfig: Record<string, { color: string; text: string }> = {
    admin: { color: 'red', text: '超级管理员' },
    seller: { color: 'blue', text: '商家' },
    customer_service: { color: 'green', text: '客服' },
    user: { color: 'default', text: '用户' },
  };

  const config = roleConfig[role] || { color: 'default', text: role };
  return <Tag color={config.color}>{config.text}</Tag>;
};

// 获取店铺类型标签
export const getShopTypeTag = (type: string): React.ReactElement => {
  const typeConfig: Record<string, { color: string; text: string }> = {
    official: { color: 'gold', text: '官方旗舰店' },
    brand: { color: 'blue', text: '品牌专营店' },
    ordinary: { color: 'default', text: '普通店铺' },
  };

  const config = typeConfig[type] || { color: 'default', text: type };
  return <Tag color={config.color}>{config.text}</Tag>;
};

// 截断文本
export const truncateText = (text: string, maxLength: number = 50): string => {
  if (!text) return '';
  return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
};

// 生成随机ID
export const generateId = (): string => {
  return Math.random().toString(36).substr(2, 9);
};

// 防抖函数
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  delay: number
): ((...args: Parameters<T>) => void) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
};

// 节流函数
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  delay: number
): ((...args: Parameters<T>) => void) => {
  let lastCall = 0;
  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  };
};

// 深拷贝
export const deepClone = <T,>(obj: T): T => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime()) as any;
  if (obj instanceof Array) return obj.map(item => deepClone(item)) as any;
  if (typeof obj === 'object') {
    const clonedObj = {} as any;
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
  return obj;
};

// 检查是否为空值
export const isEmpty = (value: any): boolean => {
  if (value === null || value === undefined) return true;
  if (typeof value === 'string') return value.trim() === '';
  if (Array.isArray(value)) return value.length === 0;
  if (typeof value === 'object') return Object.keys(value).length === 0;
  return false;
};

// 格式化文件大小
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 生成颜色
export const generateColor = (str: string): string => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  const color = Math.abs(hash).toString(16).substring(0, 6);
  return '#' + '000000'.substring(0, 6 - color.length) + color;
};
